package com.eachonline.smart.web.user.order;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.eachonline.core.JsonResult;
import com.eachonline.smart.model.SmartCourse;
import com.eachonline.smart.model.SmartOrderRecord;
import com.eachonline.smart.model.SmartOrderRecordExample;
import com.eachonline.smart.model.SmartUser;
import com.eachonline.smart.model.SmartUserCourse;
import com.eachonline.smart.model.SmartUserCourseExample;
import com.eachonline.smart.service.ClassTeacherService;
import com.eachonline.smart.service.CourseService;
import com.eachonline.smart.service.OrderRecordService;
import com.eachonline.smart.service.UserCourseService;
import com.eachonline.smart.util.OrderStatus;
import com.eachonline.smart.util.TradeNoGenerater;
import com.eachonline.smart.web.common.CommonUtil;
import com.eachonline.smart.web.pay.alipay.config.AlipayConfig;
import com.eachonline.smart.web.pay.alipay.util.AlipayNotify;
import com.eachonline.smart.web.pay.alipay.util.AlipaySubmit;
import com.eachonline.smart.web.pay.wxpay.Notify;
import com.eachonline.smart.web.pay.wxpay.WxPayDto;
import com.eachonline.smart.web.pay.wxpay.WxPayService;
import com.eachonline.util.StringUtil;
import com.eachonline.util.UUIDUtil;

@Controller
@RequestMapping("/trade")
public class SmartTradeController {
	
	@Autowired
	public CourseService coursesService;
	
	
	@Autowired
	public UserCourseService userCourseService;
	
	
	@Autowired
	public OrderRecordService orderRecordService;
	
	
	@Autowired
	public ClassTeacherService  classTeacherService;
	
	private static String API_URL="http://pan.baidu.com/share/qrcode?w=200&h=200&url=";
	
	private static final Logger LOGGER = Logger.getLogger(SmartTradeController.class);
	
	

	 /**
    * 获取微信支付的二维码
    * @param session
    * @return  
	 * @throws UnsupportedEncodingException 
    * @Description:
    */
   @RequestMapping(value="/wxpay", method = { RequestMethod.POST })
   @ResponseBody
	public JsonResult  getWXpayUrl(HttpServletRequest request, HttpServletResponse response,String orderNo) 
	{
	   if(orderRecordService.verifyIsMainTradeNo(orderNo))
	   {
		    SmartOrderRecordExample exaOrder=new SmartOrderRecordExample();
		    exaOrder.createCriteria().andMainOrderNoEqualTo(orderNo).andOrderStatusEqualTo(OrderStatus.WAIT);
		    List<SmartOrderRecord>  list=orderRecordService.selectByExample(exaOrder);
		    if(list.isEmpty())
		    {
		    	return  new JsonResult(false, "该订单不存在");
		    }
		    double totalFee=0.00;
		    for(SmartOrderRecord record:list)
		    {
		    	totalFee=totalFee+record.getBusinessFee();
		    }
		    
		    SmartOrderRecord  record=list.get(0);
		    WxPayDto tpWxPay1 = new WxPayDto();
		    tpWxPay1.setBody(record.getOrderName());
		    tpWxPay1.setOrderId(orderNo+WxPayService.getNonceStr());
		    tpWxPay1.setSpbillCreateIp("127.0.0.1");
		    tpWxPay1.setTotalFee(totalFee+"");
		    
		    Map<String,Object> datamap=new HashMap<String, Object>();
		    datamap.put("wxCodeUrl",  API_URL+WxPayService.getCodeurl(tpWxPay1));
		   	return  new JsonResult(true, "成功",datamap);
		   
	   }else{
		   
		   
		   SmartOrderRecordExample exaOrder=new SmartOrderRecordExample();
		    exaOrder.createCriteria().andOrderNoEqualTo(orderNo).andOrderStatusEqualTo(OrderStatus.WAIT);
		    List<SmartOrderRecord>  list=orderRecordService.selectByExample(exaOrder);
		    if(list.isEmpty())
		    {
		    	return  new JsonResult(false, "该订单不存在");
		    }
		    SmartOrderRecord  record=list.get(0);
		    WxPayDto tpWxPay1 = new WxPayDto();
		    tpWxPay1.setBody(record.getOrderName());
		    tpWxPay1.setOrderId(orderNo+WxPayService.getNonceStr());
		    tpWxPay1.setSpbillCreateIp("127.0.0.1");
		    tpWxPay1.setTotalFee(record.getBusinessFee()+"");
		    
		    Map<String,Object> datamap=new HashMap<String, Object>();
		    datamap.put("wxCodeUrl",  API_URL+WxPayService.getCodeurl(tpWxPay1));
		   	return  new JsonResult(true, "成功",datamap);
		   
	   }
	    
	}
		

	
	

   /**
   *  0元下单
   * @param session
   * @return  
	 * @throws UnsupportedEncodingException 
   * @Description:
   */
  @RequestMapping(value="/joinMyCourse")
  @ResponseBody
	public JsonResult  joinMyCourse(HttpServletRequest request,String courseId)
	{
			
		SmartCourse course=  coursesService.selectByPrimaryKey(courseId);
		if(course==null)
		{
			return new JsonResult(false, "您购买的课程不存在。");
		}
	 
		if(course.getCoursePrice()!=0)
		{
			return new JsonResult(false, "您购买的课程未支付");
		}
		SmartUser user=CommonUtil.getCurrentUser(request);
		String userId=user.getSid();
		if(userId==course.getUserSid()||userId.equals(course.getUserSid()))
		{
			return new JsonResult("6002", "不能购买自己的课程");
		}
			
		SmartUserCourseExample suce=new SmartUserCourseExample();
		suce.createCriteria().andCourseIdEqualTo(courseId).andUserIdEqualTo(userId);
		List<SmartUserCourse> list=userCourseService.selectByExample(suce);
		if(!list.isEmpty())
		{
			return new JsonResult(false, "您购买的课程已存在");
		}
		addMyCourse(courseId, userId);
		try {
			classTeacherService.joinClass(courseId, userId);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new JsonResult(false, "加入班级失败");
		}
		return new JsonResult(true, "成功");
	}
   
   
	 /**
     * 支付宝支付
     * @param session
     * @return  
	 * @throws UnsupportedEncodingException 
     * @Description:
     */
    @RequestMapping(value="/alipay")
    @ResponseBody
	public String  payMoneyByAliapi(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException
	{
		////////////////////////////////////请求参数//////////////////////////////////////

     /*   //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

        //订单名称，必填
        String subject = new String(request.getParameter("subject"));

        //付款金额，必填
        String total_fee = new String(request.getParameter("total_fee").getBytes("ISO-8859-1"),"UTF-8");

        //商品描述，可空
        String body = new String(request.getParameter("body").getBytes("ISO-8859-1"),"UTF-8");
*/
    	
    	   //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no =request.getParameter("out_trade_no");

        //订单名称，必填
        String subject = request.getParameter("subject");

        //付款金额，必填
        String total_fee = request.getParameter("total_fee");

        //商品描述，可空
        String body = request.getParameter("body");

        if(orderRecordService.verifyIsMainTradeNo(out_trade_no)){
        	subject="多个课程合并购买订单号"+out_trade_no;
        }else
        {
        	 SmartOrderRecordExample ore=new SmartOrderRecordExample();
             ore.createCriteria().andOrderNoEqualTo(out_trade_no);
            List<SmartOrderRecord> list =orderRecordService.selectByExample(ore);
            if(!list.isEmpty())
            {
         	   subject =list.get(0).getOrderName();
            }
        }
        
       
		//////////////////////////////////////////////////////////////////////////////////
		
		//把请求参数打包成数组
		Map<String, String> sParaTemp = new HashMap<String, String>();
		sParaTemp.put("service", AlipayConfig.service);
        sParaTemp.put("partner", AlipayConfig.partner);
        sParaTemp.put("seller_id", AlipayConfig.seller_email);
        sParaTemp.put("_input_charset", AlipayConfig.input_charset);
		sParaTemp.put("payment_type", AlipayConfig.payment_type);
		sParaTemp.put("notify_url", AlipayConfig.notify_url);
		sParaTemp.put("return_url", "http://jiuke100.net/user-index.html?fr=paied");
		sParaTemp.put("anti_phishing_key", AlipayConfig.anti_phishing_key);
		sParaTemp.put("exter_invoke_ip", AlipayConfig.exter_invoke_ip);
		sParaTemp.put("out_trade_no", out_trade_no);
		sParaTemp.put("subject", subject);
		sParaTemp.put("total_fee", total_fee);
		sParaTemp.put("body", body);
		//其他业务参数根据在线开发文档，添加参数.文档地址:https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.O9yorI&treeId=62&articleId=103740&docType=1
        //如sParaTemp.put("参数名","参数值");
		
		//建立请求
		String sHtmlText = AlipaySubmit.buildRequest(sParaTemp,"get","确认");
		return sHtmlText;
	}
    
    
    

  /**
   * 用户合并购买下单
   * @param session
   * @return  
	 * @throws UnsupportedEncodingException 
   * @Description:
   */
  @RequestMapping(value="/mergePayOrder", method = { RequestMethod.POST })
  @ResponseBody
	public JsonResult  mergePayOrder(HttpServletRequest request, String businessIdStr) 
	{
	
	    businessIdStr = businessIdStr.substring(1, businessIdStr.length() -1);
        String businessId[]=businessIdStr.split(",");	
        if(businessId.length<=0)
        {
        	return new JsonResult(false, "课程ID不能为空");
        }
        
        for(int i=0;i<businessId.length;i++)
        {
        	 if(com.eachonline.util.StringUtil.isEmpty(businessId[i]))
     	    {
     		   return new JsonResult(false, "课程ID不能为空");
     	    }
     	    SmartUser user =CommonUtil.getCurrentUser(request);
     	
     	    
     	    SmartOrderRecord orderRecord= orderRecordService.selectByPrimaryKey(businessId[i]);
     	    if(orderRecord==null)
    	    {
    	    	return new JsonResult(false, "订单错误。");
    	    }
     	    
     	    if(!orderRecord.getOrderStatus().equals(OrderStatus.WAIT))
     	    {
     	    	return new JsonResult(false, "订单状态错误");
     	    }
     	   
     	    SmartCourse  course= coursesService.selectByPrimaryKey(orderRecord.getBusinessId());
     	    if(course==null)
     	    {
     	    	return new JsonResult(false, "您购买的课程不存在。");
     	    }
     	    
     	    if((course.getCourseEndTime().compareTo(new Date()))<0)
     	    {
     	    	return new JsonResult(false, "您购买的课程已经结束。");
     	    }
     	   
        }
        
        String mainTradeNo=TradeNoGenerater.getInstance().generaterMainTradeNo();
        for(int i=0;i<businessId.length;i++)
        {
        	   SmartOrderRecord orderRecord= orderRecordService.selectByPrimaryKey(businessId[i]);
        	   orderRecord.setMainOrderNo(mainTradeNo);
        	   orderRecordService.updateByPrimaryKeySelective(orderRecord);
        }
	    
	    Map<String,Object> dataMap=new HashMap<String, Object>();
	    dataMap.put("orderNo", mainTradeNo);
	  
		return new JsonResult(true, dataMap);
	 
		
	}
    
    

	 /**
    * 用户购买下单
    * @param session
    * @return  
	 * @throws UnsupportedEncodingException 
    * @Description:
    */
   @RequestMapping(value="/payOrder", method = { RequestMethod.POST })
   @ResponseBody
	public JsonResult  payOrder(HttpServletRequest request, String businessId) 
	{
	
	    if(com.eachonline.util.StringUtil.isEmpty(businessId))
	    {
		   return new JsonResult(false, "课程ID不能为空");
	    }
	    SmartUser user =CommonUtil.getCurrentUser(request);
	
	    SmartCourse  course= coursesService.selectByPrimaryKey(businessId);
	    if(course==null)
	    {
	    	return new JsonResult(false, "您购买的课程不存在。");
	    }
	    String userId=user.getSid();
	    if(userId==course.getUserSid()||userId.equals(course.getUserSid()))
		{
	    	return new JsonResult("6002", "不能购买自己的课程");
		}
	    
	   /*   SmartUserCourseExample ore=new SmartUserCourseExample();
		  ore.createCriteria().andCourseIdEqualTo(businessId).andUserIdEqualTo(userId);
		  List<SmartUserCourse>  myList= userCourseService.selectByExample(ore);
		  if(!myList.isEmpty())
			 {
			  return new JsonResult("6001", "已购买了此课程");
				}
			 }*/
	    
	    if((course.getCourseEndTime().compareTo(new Date()))<0)
	    {
	    	return new JsonResult(false, "您购买的课程已经结束。");
	    }
	    
	    List<String> statusList=new ArrayList<String>();
	    statusList.add("0");
	    statusList.add("1");
	    SmartOrderRecordExample  orderExample=new SmartOrderRecordExample();
	    orderExample.createCriteria().andBusinessIdEqualTo(businessId).andOrderStatusIn(statusList).andUserIdEqualTo(user.getSid());
	    
	    List<SmartOrderRecord>  orderList=orderRecordService.selectByExample(orderExample);
	    if(orderList!=null&&orderList.size()>0)
	    {
	    	return new JsonResult("6001", "您购买的课程在我的订单中已存在，请到我的订单中查看购买");
	    }
	    String orderNo=TradeNoGenerater.getInstance().generaterPayTradeNo();
	    SmartOrderRecord orderRecord=new SmartOrderRecord();
	    orderRecord.setSid(UUIDUtil.getUUID());
	    orderRecord.setBusinessId(businessId);
	    orderRecord.setUserId(user.getSid());
	    orderRecord.setMainPic(course.getMainCoursePic());
	    orderRecord.setOrderName(course.getCourseName());
	    orderRecord.setOrderNo(orderNo);
	    orderRecord.setBusinessFee(course.getCoursePrice());
	    orderRecord.setTradeTime(new Date());
	    orderRecord.setOrderStatus(OrderStatus.WAIT);
	    orderRecord.setUserName(user.getUserName());
	    orderRecord.setUserPhone(user.getLoginName());
	    
	    int row= orderRecordService.insert(orderRecord);
	    
	    Map<String,Object> dataMap=new HashMap<String, Object>();
	    dataMap.put("orderNo", orderNo);
	   if(row>0)
	   {
		   return new JsonResult(true, dataMap);
	   }else
	   {
		   return new JsonResult(false, "下单失败");
	   }
		
	}
    
   
   

	 /**
     * 支付宝回调接口
     * @param session
     * @return  
	 * @throws UnsupportedEncodingException 
     * @Description:
     */
    @RequestMapping(value="/alipayNotify", method = { RequestMethod.POST })
    @ResponseBody
	public String  alipayNotify(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException
	{
    	Map<String,String> params = new HashMap<String,String>();
    	Map requestParams = request.getParameterMap();
    	for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
    		String name = (String) iter.next();
    		String[] values = (String[]) requestParams.get(name);
    		String valueStr = "";
    		for (int i = 0; i < values.length; i++) {
    			valueStr = (i == values.length - 1) ? valueStr + values[i]
    					: valueStr + values[i] + ",";
    		}
    		//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
    		//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
    		params.put(name, valueStr);
    	}
    	
    	//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
    	//商户订单号

    	String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

    	//支付宝交易号

    	String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

    	//交易状态
    	String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

    	//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//

    	if(AlipayNotify.verify(params)){//验证成功
    		//////////////////////////////////////////////////////////////////////////////////////////
              if (trade_status.equals("TRADE_SUCCESS")){
    			//判断该笔订单是否在商户网站中已经做过处理
    				//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
    				//请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
    				//如果有做过处理，不执行商户的业务程序
            	  try {
					orderRecordService.updateOrderStatusAndStudy(out_trade_no);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    			//注意：
    			//付款完成后，支付宝系统发送该交易状态通知
    		}else{
    			
    			try {
					orderRecordService.updateOrderStatusOnFail(out_trade_no);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    			
    		}

    		//——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
    			
    	return "sucess"	;//请不要修改或删除

    		//////////////////////////////////////////////////////////////////////////////////////////
    	}else{//验证失败
    		return  "fail";
    	}
	}
  
    
    /**
     * 获取微信支付的状态信息
     * @param session
     * @return  
 	 * @throws UnsupportedEncodingException 
     * @Description:
     */
    @RequestMapping(value="/wxPayStatus", method = { RequestMethod.POST })
    @ResponseBody
    public JsonResult getWxPayStatus(HttpServletRequest request,HttpServletResponse response,String orderNo) {
    	if(orderRecordService.verifyIsMainTradeNo(orderNo))
    	{

        	SmartUser user =CommonUtil.getCurrentUser(request);
        	SmartOrderRecordExample exaOrder=new SmartOrderRecordExample();
      	    exaOrder.createCriteria().andMainOrderNoEqualTo(orderNo).andUserIdEqualTo(user.getSid());
      	    List<SmartOrderRecord>  list=orderRecordService.selectByExample(exaOrder);
      	    if(list.isEmpty())
      	    {
      	    	return  new JsonResult(false, "该订单不存在");
      	    }
      	    SmartOrderRecord  record=list.get(0);
        	Map<String,String> dataMap=new HashMap<String,String>();
        	dataMap.put("orderStatus", record.getOrderStatus());
        	return  new JsonResult(true, "成功",dataMap);
    		
    	}else
    	{
    		

        	SmartUser user =CommonUtil.getCurrentUser(request);
        	SmartOrderRecordExample exaOrder=new SmartOrderRecordExample();
      	    exaOrder.createCriteria().andOrderNoEqualTo(orderNo).andUserIdEqualTo(user.getSid());
      	    List<SmartOrderRecord>  list=orderRecordService.selectByExample(exaOrder);
      	    if(list.isEmpty())
      	    {
      	    	return  new JsonResult(false, "该订单不存在");
      	    }
      	    SmartOrderRecord  record=list.get(0);
        	Map<String,String> dataMap=new HashMap<String,String>();
        	dataMap.put("orderStatus", record.getOrderStatus());
        	return  new JsonResult(true, "成功",dataMap);
    		
    	}
    	
	}
    
    public static void main(String[] args) {
		
    	String str="{12312,123123}";
    	 str = str.substring(1, str.length() -1);
    	System.out.println(str.split(",")[0]);

    	
    	
	}
    
    /**
    * 微信回调接口
    * @param session
    * @return  
	 * @throws UnsupportedEncodingException 
    * @Description:
    */
   @RequestMapping(value="/wxpayNotify", method = { RequestMethod.POST })
   @ResponseBody
   public void wxpayNotify(HttpServletRequest request,HttpServletResponse response) throws Exception{
	try {
			LOGGER.info(" begin:notifyPayForwx:------------------------------------------");
		   InputStream inStream=request.getInputStream();
		   ByteArrayOutputStream outStream=new ByteArrayOutputStream();
		   byte[] buffer=new byte[1024];
		   int len = 0;
		   while((len =inStream.read(buffer)) !=-1){
			   outStream.write(buffer, 0, len);
		   }
		   LOGGER.info("pay Success=============================");
		   outStream.close();
		   inStream.close();

		   //获取微信调用我们的notify_url的返回信息
		   String result=new String(outStream.toByteArray(),"utf-8");
		  
		   Map<String,Object> map=Notify.parseXmlToList2(result);
			LOGGER.info("wx-支付:------------------------------------------"+map);
	    	String  out_trade_no=map.get("out_trade_no")+"";
	    	if(out_trade_no.length()>20)
	    	{
	    		out_trade_no=out_trade_no.substring(0, out_trade_no.length()-3);
	    	}
	    	
		   if(map.get("return_code").toString().equalsIgnoreCase("SUCCESS"))
		   {
			    
			   try {
					orderRecordService.updateOrderStatusAndStudy(out_trade_no);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
					
		  }else{
  			
  			try {
					orderRecordService.updateOrderStatusOnFail(out_trade_no);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
  			
  		}
		   response.getWriter().write(setXML("SUCCESS", "OK"));;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				  response.getWriter().write(setXML("FAIL", "ERROR"));;
			}
		 response.getWriter().write(setXML("FAIL", "ERROR"));
		   
	 }

   
   /**
	 * 微信回调接口
	 * @param return_code
	 * @param return_msg
	 * @return
	 */
	public static String setXML(String return_code,String return_msg){
		return "<xml><return_code><![CDATA["+return_code+
				"]]></return_code><return_msg><![CDATA["+return_msg+
				"]]></return_msg></xml>";
	}
	
	
	
	  
		public void  addStudyCourseNum(String bussinessId)
		{
			SmartCourse course=coursesService.selectByPrimaryKey(bussinessId);
			String studyNum=course.getStudyNum();
			if(StringUtil.isEmpty(studyNum))
			{
				studyNum="0";
			}
			int num=0;
			try {
				  num=Integer.valueOf(studyNum)+1;
			} catch (Exception e) {
				// TODO: handle exception
				  num=1;
			}
		   
		    course.setStudyNum(num+"");
		    coursesService.updateByPrimaryKeySelective(course);
		    
		}

	    /**
	     * 把课程添加到我的课程中
	     * @param BusinessId
	     */
		public void addMyCourse(String BusinessId,String userId)
		{
			SmartUserCourse  userCourse=new SmartUserCourse();
			userCourse.setSid(UUIDUtil.getUUID());
			userCourse.setCreateTime(new Date());
			userCourse.setCourseId(BusinessId);
			userCourse.setUserId(userId);
			userCourseService.insert(userCourse);
			addStudyCourseNum(BusinessId);
		}

}
